/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.session;

import com.thienloc.omap.entity.TblConfRate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author duongnv
 */
@Stateless
public class ScratchConfigRateFacade extends AbstractFacade<TblConfRate> {

    @PersistenceContext(unitName = "omapPU")
    private EntityManager em;

    public ScratchConfigRateFacade() {
        super(TblConfRate.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public TblConfRate findByLevelId(int levelId) {
        TblConfRate result = null;
        try {
            TypedQuery<TblConfRate> q = em.createNamedQuery("TblConfRate.findByLevelId", TblConfRate.class);
            q.setParameter("levelId", levelId);
            result = q.getSingleResult();
            return result;
        } catch (Exception ex) {
            Logger.getLogger(ScratchConfigRateFacade.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public TblConfRate update(int level, int bottom, int up, double rate) {
        TblConfRate tbl = new TblConfRate();
        try {
            tbl.setLevelId(level);
            tbl.setBottomValue(bottom);
            tbl.setUpValue(up);
            tbl.setRate(rate);
            TblConfRate result = findByLevelId(level);
            if (result == null) {
                em.persist(tbl);
                result = tbl;
            } else {
                tbl.setId(result.getId());
                result = em.merge(tbl);
            }
            return result;
        } catch (Exception ex) {
            Logger.getLogger(ScratchAccountFacade.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
